import { resolve } from "path";
import express from "express";
import multer from "multer";
import cors from "cors";
import { apiPort } from "@/configs/api";
import { ipFilter } from "@/middlewares/ip-filter";
import { rateLimiter } from "@/middlewares/rate-limiter";
import { authVerifier } from "@/middlewares/auth-verifier";
import { notFoundHandler } from "@/middlewares/not-found-handler";
import { errorHandler } from "@/middlewares/error-handler";
import authRouter from "@/routes/auth";
import fileRouter from "@/routes/file";
import devRouter from "@/routes/dev";
import helpRouter from "@/routes/help";
import userRouter from "@/routes/user";
import signupRouter from "@/routes/signup";

export const app = express();
export const expressInit = () => {
	const staticPath = resolve(import.meta.dirname, "../../public");
	const upload = multer({ dest: staticPath + "/temp" });
	app.use(upload.any());
	app.use(express.static(staticPath));
	app.use(express.json());
	app.use(express.urlencoded({ extended: true }));
	app.use(cors());
	app.set("trust proxy", 1);
	app.get("/shuang-yuan-zhi", (_request, response) => response.sendFile(staticPath + "/web/signup-h5/index.html"));
	app.use(ipFilter);
	app.use(rateLimiter);
	app.use("/shuang-yuan-zhi/api/dev", devRouter);
	app.use("/shuang-yuan-zhi/api/help", helpRouter);
	app.use("/shuang-yuan-zhi/api/auth", authRouter);
	app.use(authVerifier);
	app.use("/shuang-yuan-zhi/api/file", fileRouter);
	app.use("/shuang-yuan-zhi/api/user", userRouter);
	app.use("/shuang-yuan-zhi/api/signup", signupRouter);
	app.use(notFoundHandler);
	app.use(errorHandler);
	app.listen(apiPort, () => console.log("server is running"));
};
